<template>
  <m-container class="confirm">
    <in-work-scan :palletCode="info.palletCode" :show-btn="false" />
    <inventory-card :modal="info">
      <view class="grid">
        <view class="item">
          <text>实际数量(箱)</text>
          <view>{{ totalPackageNumber.length }}</view>
        </view>
        <view class="item">
          <text>拣货数量(箱)</text>
          <view>{{ totalPickNumber }}</view>
        </view>
        <view class="item">
          <text>偏差数量(箱)</text>
          <m-text :color="totalDeviationNumber ? 'red' : '#333'">
            {{ totalDeviationNumber }}
          </m-text>
        </view>
      </view>

      <view class="box" v-if="totalDeviationNumber">
        <text class="tip"><m-text color="red">*</m-text> 审批申请原因</text>
        <m-textarea
          placeholder="请填写审批申请原因..."
          limitPosition="right"
          v-model="form.applyReason"
          :maxlength="200"
        />
      </view>
    </inventory-card>

    <m-cell-group weight="label" :border="false" v-if="showStartCode">
      <m-cell label="当前站点" size="xs" />
      <m-cell title="地标码" size="xs">
        <view
          class="center"
          slot="center"
          style="margin-left: 30rpx; display: flex; justify-content: space-between; align-items: center"
        >
          <m-text :line="1"> {{ form.deliveryStartCode }}</m-text>
          <m-button
            shape="round"
            background="#fff"
            size="md"
            plain
            height="76rpx"
            width="220rpx"
            @click="handleScanStartCode"
          >
            扫描地标码
          </m-button>
        </view>
      </m-cell>
    </m-cell-group>

    <m-cell-group weight="label" :border="false">
      <m-cell label="回库方式" size="xs" />
      <m-cell title="回库方式" size="xs">
        <view class="center" slot="center" style="margin-left: 30rpx" :key="imsType">
          <m-radio-group inline v-model="form.deliveryType" v-if="imsType === 1">
            <m-radio :label="+val" v-for="(key, val) in deliveryTypeMap" :key="val">{{ key }} </m-radio>
          </m-radio-group>

          <view v-else>堆垛机/四向车</view>
        </view>
      </m-cell>
    </m-cell-group>

    <m-cell-group weight="label" :border="false" style="margin-top: -20rpx">
      <m-cell label="目标站点" size="xs" />
      <m-cell size="xs">
        <view slot="center" class="row_radio center">
          <m-radio-button>
            <u-image width="42rpx" height="46rpx" src="@/static/hg.png" />
            <text>库位</text>
          </m-radio-button>

          <m-radio-group v-model="value">
            <m-radio
              :label="item.value"
              v-for="(item, index) in options"
              :key="index"
              @click="handleRadioClick"
              :disabled="item.disabled"
            >
              {{ item.name }}
            </m-radio>
          </m-radio-group>
        </view>
      </m-cell>
    </m-cell-group>

    <inventory-station-layer v-model="visible" @confirm="handleDeliveryTargetCode" :id="info.imsId" />

    <m-fixed>
      <view class="footer">
        <m-button
          width="48%"
          size="xl"
          @click="handleClickSubmit"
          background="#FF831F"
          :disabled="loading1 || clickSubmit"
          :loading="loading1"
          v-if="totalDeviationNumber"
        >
          盘点审批
        </m-button>
        <m-button
          :width="totalDeviationNumber ? '48%' : '100%'"
          size="xl"
          @click="handleClickSave"
          :disabled="loading"
          :loading="loading"
        >
          回库
        </m-button>
      </view>
    </m-fixed>
  </m-container>
</template>

<script>
const barcodeModel = uni.requireNativePlugin('iData-BarcodePlugin-BarcodeModule')
const globalEvent = uni.requireNativePlugin('globalEvent')
import { deliveryTypeMap } from '@/utils/constant'
import { mapState } from 'vuex'
import { inventory, addInventory } from '@/api/modules/inventory'
import { showModal } from '@/hooks'
import { getIms } from '@/api/modules/in-work'
import { router } from '@/router'

export default {
  data() {
    return {
      showStartCode: false,
      palletCode: '',
      deliveryTypeMap,
      clickSubmit: false,
      form: {
        deliveryType: 2,
        applyReason: '',
        deliveryTargetCode: null,
        deliveryStartCode: null,
      },
      options: [
        { name: '系统分配', value: 1, disabled: false },
        { name: '人工分配', value: 2, disabled: true },
      ],
      value: 1,
      visible: false,
      loading: false,
      loading1: false,
      imsType: 0,
    }
  },
  computed: {
    ...mapState({
      info: (state) => state.inventory.form,
    }),
    totalPackageNumber() {
      return this.info.imsInventoryDetailList
    },
    totalPickNumber() {
      return this.totalPackageNumber.filter((item) => item.status === 1).length
    },
    totalDeviationNumber() {
      return this.totalPackageNumber.length - this.totalPickNumber
    },
  },
  async onLoad({ deliveryStartCode }) {
    if (deliveryStartCode) {
      this.form.deliveryStartCode = deliveryStartCode
    } else {
      this.showStartCode = true
    }

    const {
      data: { imsType },
    } = await getIms(this.info.imsId)
    this.imsType = imsType

    barcodeModel.initScan()
    globalEvent.addEventListener('iDataBarcodeEvent', ({ barcode }) => {
      if (this.$Router.currentRoute.name !== 'ConfirmInventory') {
        return
      }

      if (barcode.startsWith('WMS-P-')) {
        uni.showToast({
          title: '请扫码正确的地标码！',
          icon: 'none',
        })
        return
      }
      this.form.deliveryStartCode = barcode
    })
  },
  methods: {
    handleScanStartCode() {
      barcodeModel.scanStart((ret) => {
        console.log(7)
      })
    },
    handleRadioClick(e) {
      this.form = {
        ...this.form,
        stationId: null,
        stationCode: null,
        stackNo: null,
        levelNo: null,
        locationNo: null,
        deliveryTargetCode: null,
      }
      this.options[1].name = '人工分配'
      this.visible = e === 2
    },
    handleDeliveryTargetCode(e) {
      this.form = {
        ...this.form,
        ...e,
        deliveryTargetCode: e.stationCode,
      }

      this.options[1].name = `人工分配 ${e.imsText}/${e.stackNo}-${e.levelNo}-${e.locationNo}`
    },
    getParams() {
      return {
        toStorageLocationType: 3,
        totalPackageNumber: this.totalPackageNumber.length,
        totalPickNumber: this.totalPickNumber,
        totalDeviationNumber: this.totalDeviationNumber,
        ...this.info,
        ...this.form,
        status: 0,
      }
    },
    async handleClickSave() {
      let title = '回库提示'
      let content = '请问您确认是否回库？'

      if (this.totalDeviationNumber && !this.clickSubmit) {
        title = '盘点审批提示'
        content = '请您确认是否要要回库？您还未点击盘点审核，确认回库后无法再次修改。'
      }

      if (this.form.deliveryStartCode === '') {
        uni.showToast({
          title: '请扫码起始点地标码！',
          icon: 'none',
        })
        return
      }

      showModal({
        title,
        content,
        showCancelButton: true,
        slot: true,
        confirm: async () => {
          this.loading = true
          const params = this.getParams()
          if (this.value === 1) {
            delete params['stationCode']
            delete params['stationId']
          }
          try {
            await addInventory(params)
            uni.showToast({
              title: '操作成功',
              success: () => {
                uni.$emit('clear')
                router.back(2)
              },
            })
          } catch (e) {}
          this.loading = false
        },
      })
    },
    async handleClickSubmit() {
      if (this.form.applyReason === '') {
        uni.showToast({
          title: '请输入申请原因',
          icon: 'none',
        })
        return
      }

      if (+this.value === 2 && !this.form.deliveryTargetCode) {
        uni.showToast({
          title: '请选择分配库位',
          icon: 'none',
        })
        return
      }

      showModal({
        title: '盘点审批提示',
        content: '请您确认是否要进入盘点审核流程吗？确认后将不可再进行修改。',
        showCancelButton: true,
        slot: true,
        confirm: async () => {
          this.clickSubmit = true
          this.loading1 = true
          try {
            await inventory(this.getParams())
            uni.showToast({
              title: '已提交',
            })
          } catch (e) {}
          this.loading1 = false
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.confirm {
  .grid {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20rpx;

    .item {
      background: #f0f5fc;
      overflow: hidden;
      font-weight: bold;
      font-size: 32rpx;
      color: #2d3a47;
      text-align: center;
      flex: 1;
      padding: 13rpx 0;
      display: flex;
      flex-direction: column;
      &:first-child {
        border-radius: 12rpx 0 0 12rpx;
      }
      &:last-child {
        border-radius: 0 12rpx 12rpx 0;
      }
      text {
        font-size: 24rpx;
        color: #566675;
        margin-bottom: 18rpx;
      }
    }
  }

  .row_radio {
    margin-left: 30rpx;
    display: flex;
    & > .radio {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      min-width: 196rpx;
      height: 156rpx;
      background: #fff;
      border-color: #d7dce0;
      color: #748da7;
      &--checked {
        border-color: #248dfa;
        color: #248dfa;
      }
      text {
        margin-top: 19rpx;
        font-size: 28rpx;
        color: #748da7;
      }
    }
    ::v-deep {
      .radio-group__content {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        height: 156rpx;
      }
    }
  }

  .box {
    margin: 0 20rpx;
    padding-bottom: 20rpx;
    .tip {
      color: #748da7;
      margin-bottom: 20rpx;
      display: block;
    }
  }
  .footer {
    display: flex;
    justify-content: space-between;
  }
}
</style>
